import json
import traceback
from typing import Union

from aweirunner.dto.tree_dto import TreeUniqueIn, TreeOut
from aweirunner.models import Relation
from aweirunner.utils.response import StandResponse, TREE_ADD_SUCCESS, TREE_UPDATE_SUCCESS
from aweirunner.utils.tree import get_tree_max_id
from curd.base_curd import GenericCURD
from auto_dj_test.conf.MyLogger import MyLogger


class TreeService(MyLogger):

    def __init__(self):
        super().__init__(f"{__name__}:{self.__class__.__name__}")
        self.model = Relation
        self.curd = GenericCURD(self.model)

    def get_or_create(self, query: TreeUniqueIn):
        # 定义默认的树
        default_tree: list = [{"id": 1, "label": "default node", "children": []}]
        self.logger.warning("1111")
        # created 是否是新创建的对象。True，表示新创建了一个对象；False，表示已经存在的对象被找到了
        tree_obj, created = self.curd.get_or_create(
            filter_kwargs=query.model_dump(),
            defaults={"tree": default_tree, "project_id": query.project_id}
        )
        self.logger.warning(f"tree_obj:{tree_obj}.created:{created}")
        if created:
            self.logger.info(f"树不存在，需要创建默认节点{query}")
            body: list[dict] = tree_obj.tree
        else:
            self.logger.info(f"查询树存在 {query=}")
            body: list[dict] = eval(tree_obj.tree)
            self.logger.info(f"查询body {body}")
        tree = {
            "tree": body,
            "id": tree_obj.id,
            "success": True,
            "max": get_tree_max_id(body),
        }
        return StandResponse[TreeOut](**TREE_ADD_SUCCESS, data=TreeOut(**tree))

    def patch(self, pk: int, payload: TreeUniqueIn) -> StandResponse[Union[TreeOut, None]]:
        try:
            pk: int = self.curd.update_obj_by_pk(pk, None, payload.model_dump())
        except Exception as e:
            err: str = traceback.format_exc()
            self.logger.warning(f"update tree {err=}")
            return StandResponse[None](code="9999", success=False, msg=err, data=None)
        return StandResponse[TreeOut](
            **TREE_UPDATE_SUCCESS,
            data=TreeOut(tree=payload.tree, id=pk, max=get_tree_max_id(payload.tree)),
        )


tree_service = TreeService()
